package cn.ywang;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Auther: BeatificWang
 * @Date: 2018/11/3 10:01
 */
@Slf4j
public class ServerHandler implements Runnable {

	private Socket socket;

	public ServerHandler(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		BufferedReader reader = null;
		PrintWriter writer = null;
		try {
			reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
			writer = new PrintWriter(this.socket.getOutputStream(), true);
			String content;
			String result;
			Scanner scanner = new Scanner(System.in);
			while (true) {
				content = reader.readLine();
				if (content == null) {
					break;
				}
				log.info("服务器接收到的消息为:" + content);
				System.out.println("客户端:" + content);
				result = scanner.next();
				writer.println(result);
				System.out.println("服务器端：" + result);
			}
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				reader = null;
			}
			if (writer != null) {
				writer.close();
			}
			if (this.socket != null) {
				try {
					this.socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				this.socket = null;
			}
		}
	}
}
